import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { setToken, getToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: () => (
    {
      token: getToken() || '',
      userInfo: {}
    }
  ),
  mutations: {
    setToken(state, token) {
      // 保存在vuex中
      state.token = token
      // 保存在cookie中
      setToken(token)
    },
    // 设置用户信息
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    // 删除用户信息
    reomveUserInfo(state) {
      state.userInfo = {}
      state.token = ''
    }

  },
  actions: {
    asyncSetToken(ctx, data) {
      return new Promise((resolve, reject) => {
        login(data).then(res => {
          // 提交mutation函数
          ctx.commit('setToken', res)
          resolve(res)
        })
      })
    },
    // 获取用户资料action
    asyncGetUserInfo(ctx) {
      return new Promise((resolve, reject) => {
        getUserInfo().then((res) => {
          getUserDetailById(res.userId).then(imgInfo => {
            ctx.commit('setUserInfo', { ...res, ...imgInfo })
            resolve({ ...res, ...imgInfo })
          })
        })
      })
    }

  }
}
